package com.ylxin.smartplatform.controller.advice;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ylxin.smartplatform.constans.ResultCode;
import com.ylxin.smartplatform.dto.R;
import com.ylxin.smartplatform.exceptions.MyBaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

/**
 * @author 29048
 * @version V1.0
 * @Project smartplatform
 * @Package com.ylxin.smartplatform.controller.advice
 * @Description: Create by 杨立新 @Date 2022/9/5 16:38
 */
@RestControllerAdvice
public class MyControllerAdvice {

    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    /**
     * 处理我们的自定义异常的
     * @param exception
     * @return
     */
    @ExceptionHandler(MyBaseException.class)
    public R procesBaseException(MyBaseException exception){
        exception.printStackTrace();
        return R.getResult(exception.getCode(),exception.getMessage());
    }

    /**
     * 处理请求参数校验的异常
     * @param exception
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R processMethodArgumentNotValidException(MethodArgumentNotValidException exception){

//        exception.getBindingResult().getAllErrors().forEach(objectError -> {
//            String defaultMessage = objectError.getDefaultMessage();
//            System.err.println(defaultMessage);
//        });

        String defaultMessage = exception.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        try {
            //将我们自定义的异常字符串转成map，然后从里面获取到我们传递的code 和 msg
            Map map = objectMapper.readValue(defaultMessage, Map.class);
            return R.getResult((Integer) map.get("code"), (String)map.get("msg"));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return R.ERROR();
    }

    @ExceptionHandler(Exception.class)
    public R processBaseException(Exception exception){
        exception.printStackTrace();
        return R.getResult(ResultCode.FAIL,"网络异常，请检查您的网络");
    }
}
